package org.sean.framework.web.converter;


import org.sean.framework.logging.Logger;
import org.sean.framework.util.GSONUtil;
import org.sean.framework.util.StringUtil;
import org.sean.framework.web.interceptor.ApiInterceptor;
import org.springframework.http.converter.json.AbstractJsonHttpMessageConverter;

import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Type;

/**
 * JSON转换器
 *
 * @author xielei
 */
public class GsonHttpMessageConverter extends AbstractJsonHttpMessageConverter {

    private final Logger log = Logger.newInstance(this.getClass());

    @Override
    protected boolean supports(Class<?> clazz) {
        return Boolean.TRUE.equals(ApiInterceptor.isExecuted()) && super.supports(clazz);
    }


    @Override
    protected Object readInternal(Type resolvedType, Reader reader) throws Exception {
        return GSONUtil.json2Obj(reader, resolvedType);
    }

    @Override
    protected void writeInternal(Object o, Type type, Writer writer) throws Exception {
        if (o instanceof CharSequence) {
            writer.write(o.toString());
            writer.flush();
        } else {
            String result = GSONUtil.obj2Json(o);
            log.debug(() -> {
                String response = "无内容";
                if (StringUtil.isNotEmpty(result)) {
                    if (result.length() < 10000) {
                        response = result;
                    } else {
                        response = "日志太长不打印.(code_need_change)";
                    }
                }
                return StringUtil.formatContent("Response Body : {0}", response);
            });

            writer.write(result);
            writer.flush();
        }
    }
}
